/**
 * 全局状态管理
 * 使用Vue3的reactive和provide/inject实现简单的状态管理
 */

import { reactive, computed } from 'vue'

// 全局状态
const state = reactive({
  // 用户信息
  userInfo: null,
  isLoggedIn: false,
  accessToken: '',
  refreshToken: '',
  
  // 目的港信息
  selectedPort: null,
  ports: [],
  
  // 购物车
  cartCount: 0,
  personalCart: [], // 个人购物车
  shipCart: [], // 船舶购物车
  
  // 系统配置
  systemConfig: {
    version: '1.0.0',
    apiBaseUrl: 'https://api.oceanbridge.com',
    uploadUrl: 'https://upload.oceanbridge.com',
    staticUrl: 'https://static.oceanbridge.com'
  },
  
  // 应用状态
  isNetworkConnected: true,
  currentTabIndex: 0,
  
  // 消息相关
  unreadMessageCount: 0,
  conversations: [],
  
  // 搜索历史
  searchHistory: []
})

// Getters（计算属性）
const getters = {
  // 是否已登录
  isAuthenticated: computed(() => state.isLoggedIn && state.accessToken),
  
  // 购物车总数量
  totalCartCount: computed(() => {
    return state.personalCart.length + state.shipCart.length
  }),
  
  // 个人购物车商品数量
  personalCartCount: computed(() => {
    return state.personalCart.reduce((total, item) => total + item.quantity, 0)
  }),
  
  // 船舶购物车商品数量
  shipCartCount: computed(() => {
    return state.shipCart.reduce((total, item) => total + item.quantity, 0)
  }),
  
  // 用户昵称
  userName: computed(() => {
    return state.userInfo?.nickname || state.userInfo?.username || state.userInfo?.email || '未登录'
  }),
  
  // 用户头像
  userAvatar: computed(() => {
    return state.userInfo?.avatar || '/static/images/default-avatar.png'
  }),
  
  // 是否已选择目的港
  hasSelectedPort: computed(() => {
    return !!state.selectedPort
  }),
  
  // 目的港名称
  portName: computed(() => {
    return state.selectedPort?.name || '请选择目的港'
  })
}

// Actions（操作方法）
const actions = {
  // 设置用户信息
  setUserInfo(userInfo) {
    state.userInfo = userInfo
    state.isLoggedIn = !!userInfo
    
    // 持久化存储
    if (userInfo) {
      uni.setStorageSync('userInfo', userInfo)
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  
  // 设置accessToken
  setAccessToken(token) {
    state.accessToken = token
    
    // 持久化存储
    if (token) {
      uni.setStorageSync('accessToken', token)
    } else {
      uni.removeStorageSync('accessToken')
    }
  },
  
  // 设置refreshToken
  setRefreshToken(token) {
    state.refreshToken = token
    
    // 持久化存储
    if (token) {
      uni.setStorageSync('refreshToken', token)
    } else {
      uni.removeStorageSync('refreshToken')
    }
  },
  
  // 登录
  login(userInfo, accessToken, refreshToken) {
    this.setUserInfo(userInfo)
    this.setAccessToken(accessToken)
    if (refreshToken) {
      this.setRefreshToken(refreshToken)
    }
  },
  
  // 登出
  logout() {
    state.userInfo = null
    state.isLoggedIn = false
    state.accessToken = ''
    state.refreshToken = ''
    state.personalCart = []
    state.shipCart = []
    state.cartCount = 0
    state.unreadMessageCount = 0
    state.conversations = []
    
    // 清除本地存储
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('accessToken')
    uni.removeStorageSync('refreshToken')
    uni.removeStorageSync('personalCart')
    uni.removeStorageSync('shipCart')
    
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/auth/login'
    })
  },
  
  // 设置目的港
  setSelectedPort(port) {
    state.selectedPort = port
    
    // 持久化存储
    if (port) {
      uni.setStorageSync('selectedPort', port)
    } else {
      uni.removeStorageSync('selectedPort')
    }
  },
  
  // 设置目的港列表
  setPorts(ports) {
    state.ports = ports
    uni.setStorageSync('ports', ports)
  },
  
  // 添加商品到个人购物车
  addToPersonalCart(product) {
    const existingItem = state.personalCart.find(item => 
      item.id === product.id && 
      JSON.stringify(item.specs) === JSON.stringify(product.specs)
    )
    
    if (existingItem) {
      existingItem.quantity += product.quantity || 1
    } else {
      state.personalCart.push({
        ...product,
        quantity: product.quantity || 1,
        addTime: new Date().getTime()
      })
    }
    
    this.updateCartCount()
    uni.setStorageSync('personalCart', state.personalCart)
  },
  
  // 添加商品到船舶购物车
  addToShipCart(product) {
    const existingItem = state.shipCart.find(item => 
      item.id === product.id && 
      JSON.stringify(item.specs) === JSON.stringify(product.specs)
    )
    
    if (existingItem) {
      existingItem.quantity += product.quantity || 1
    } else {
      state.shipCart.push({
        ...product,
        quantity: product.quantity || 1,
        addTime: new Date().getTime()
      })
    }
    
    this.updateCartCount()
    uni.setStorageSync('shipCart', state.shipCart)
  },
  
  // 从个人购物车移除商品
  removeFromPersonalCart(productId, specs = {}) {
    const index = state.personalCart.findIndex(item => 
      item.id === productId && 
      JSON.stringify(item.specs) === JSON.stringify(specs)
    )
    
    if (index > -1) {
      state.personalCart.splice(index, 1)
      this.updateCartCount()
      uni.setStorageSync('personalCart', state.personalCart)
    }
  },
  
  // 从船舶购物车移除商品
  removeFromShipCart(productId, specs = {}) {
    const index = state.shipCart.findIndex(item => 
      item.id === productId && 
      JSON.stringify(item.specs) === JSON.stringify(specs)
    )
    
    if (index > -1) {
      state.shipCart.splice(index, 1)
      this.updateCartCount()
      uni.setStorageSync('shipCart', state.shipCart)
    }
  },
  
  // 更新购物车商品数量
  updateCartItemQuantity(cartType, productId, specs, quantity) {
    const cart = cartType === 'personal' ? state.personalCart : state.shipCart
    const item = cart.find(item => 
      item.id === productId && 
      JSON.stringify(item.specs) === JSON.stringify(specs)
    )
    
    if (item) {
      if (quantity <= 0) {
        // 数量为0时移除商品
        if (cartType === 'personal') {
          this.removeFromPersonalCart(productId, specs)
        } else {
          this.removeFromShipCart(productId, specs)
        }
      } else {
        item.quantity = quantity
        this.updateCartCount()
        uni.setStorageSync(cartType === 'personal' ? 'personalCart' : 'shipCart', cart)
      }
    }
  },
  
  // 清空购物车
  clearCart(cartType) {
    if (cartType === 'personal') {
      state.personalCart = []
      uni.removeStorageSync('personalCart')
    } else if (cartType === 'ship') {
      state.shipCart = []
      uni.removeStorageSync('shipCart')
    } else {
      // 清空所有购物车
      state.personalCart = []
      state.shipCart = []
      uni.removeStorageSync('personalCart')
      uni.removeStorageSync('shipCart')
    }
    
    this.updateCartCount()
  },
  
  // 更新购物车数量统计
  updateCartCount() {
    state.cartCount = state.personalCart.length + state.shipCart.length
  },
  
  // 直接设置购物车数量（用于后端同步结果）
  setCartCount(count) {
    state.cartCount = Number(count) || 0
  },
  
  // 设置当前tab索引
  setCurrentTabIndex(index) {
    state.currentTabIndex = index
  },
  
  // 设置网络连接状态
  setNetworkStatus(isConnected) {
    state.isNetworkConnected = isConnected
  },
  
  // 设置未读消息数量
  setUnreadMessageCount(count) {
    state.unreadMessageCount = count
  },
  
  // 添加搜索历史
  addSearchHistory(keyword) {
    if (!keyword || keyword.trim() === '') return
    
    // 移除重复项
    const index = state.searchHistory.indexOf(keyword)
    if (index > -1) {
      state.searchHistory.splice(index, 1)
    }
    
    // 添加到开头
    state.searchHistory.unshift(keyword)
    
    // 限制历史记录数量
    if (state.searchHistory.length > 20) {
      state.searchHistory = state.searchHistory.slice(0, 20)
    }
    
    // 持久化存储
    uni.setStorageSync('searchHistory', state.searchHistory)
  },
  
  // 清除搜索历史
  clearSearchHistory() {
    state.searchHistory = []
    uni.removeStorageSync('searchHistory')
  },
  
  // 初始化状态（从本地存储恢复）
  initializeState() {
    try {
      // 恢复用户信息
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        state.userInfo = userInfo
        state.isLoggedIn = true
      }
      
      // 恢复accessToken
      const accessToken = uni.getStorageSync('accessToken')
      if (accessToken) {
        state.accessToken = accessToken
      }
      
      // 恢复refreshToken
      const refreshToken = uni.getStorageSync('refreshToken')
      if (refreshToken) {
        state.refreshToken = refreshToken
      }
      
      // 恢复目的港
      const selectedPort = uni.getStorageSync('selectedPort')
      if (selectedPort) {
        state.selectedPort = selectedPort
      }
      
      const ports = uni.getStorageSync('ports')
      if (ports) {
        state.ports = ports
      }
      
      // 恢复购物车
      const personalCart = uni.getStorageSync('personalCart')
      if (personalCart && Array.isArray(personalCart)) {
        state.personalCart = personalCart
      }
      
      const shipCart = uni.getStorageSync('shipCart')
      if (shipCart && Array.isArray(shipCart)) {
        state.shipCart = shipCart
      }
      
      // 恢复搜索历史
      const searchHistory = uni.getStorageSync('searchHistory')
      if (searchHistory && Array.isArray(searchHistory)) {
        state.searchHistory = searchHistory
      }
      
      // 更新购物车数量
      this.updateCartCount()
      
    } catch (error) {
      console.error('初始化状态失败:', error)
    }
  }
}

// 创建store实例
const store = {
  state,
  getters,
  actions
}

export default store